package com.dji.ux.sample.MQSignalClient;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * RabbitMQ工具类
 * 1、获取连接、通道对象
 * 2、关闭连接、通道对接（建议整个应用只用一个连接，不用关闭，通道也可以考虑复用，不用每次发消息都关闭）
 *
 * @author fengronghua
 * @Date 2022-01-07
 */
public class RabbitMQUtils {

    private static ConnectionFactory FACTORY;
    private static Connection CONNECTION;
    private static Channel CHANNEL;

    /**
     * 加载MQ的连接配置
     * @return
     */
    private static ConnectionFactory getFactory() {
        if (FACTORY == null) {
            FACTORY = new ConnectionFactory();
            FACTORY.setHost("8.134.15.236");
            FACTORY.setVirtualHost("illegal-dev");
            FACTORY.setUsername("luhaolin");
            FACTORY.setPassword("luhaolin_mq_1");
        }
        return FACTORY;
    }

    /**
     * 获取连接
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        if (CONNECTION == null) {
            CONNECTION = getFactory().newConnection();
        }
        return CONNECTION;
    }

    /**
     * 获取通道
     * @return
     * @throws Exception
     */
    public static Channel getChannel() throws Exception {
        if (CHANNEL == null) {
            CHANNEL = getConnection().createChannel();
        }
        return CHANNEL;
    }


    public static void sendMessage(String QUEUE_NAME, String messageStr) throws Exception {
        if (CHANNEL == null) {
            CHANNEL = getConnection().createChannel();
            CHANNEL.queueDeclare(QUEUE_NAME, true, false, false, null);
            CHANNEL.basicPublish("", QUEUE_NAME, null, messageStr.getBytes());
        }
    }

    /**
     * 关闭连接
     */
    public static void closeConnection() {
        if (CONNECTION != null) {
            try {
                CONNECTION.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭通道
     */
    public static void closeChannel() {
        if (CHANNEL != null) {
            try {
                CHANNEL.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接与通道
     */
    public static void closeALL() {
        if (CHANNEL != null) {
            try {
                CHANNEL.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (CONNECTION != null) {
            try {
                CONNECTION.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
